<template>
  <div class="container">
    <div class="app-container">
      <el-row style="text-align:center;">
        <!-- 左边 -->
        <el-col :span="4" style="border-right:1px solid #eaeef4;min-height:calc(100vh-88px);padding:0,10px">
          <el-input v-model="keyword" placeholder="输入员工姓名全员搜索" prefix-icon="el-icon-search" size="mini" style="margin:10px,0;" />
          <el-tree ref="tree" :data="departmentList" :props="{label:'name'}" default-expand-all :expand-on-click-node="false" highlight-current node-key="id" @current-change="handleCurrentChange" />
        </el-col>
        <!-- 右边 -->
        <el-col :span="20" style="margin:10px,20px;">
          <div style="text-align:right;margin-top:10px">
            <el-button type="primary" size="mini" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="show=true"> excel导入</el-button>
            <el-button size="mini" @click="exportExcel">excel导出</el-button>
          </div>
          <!--表格 -->
          <el-table
            :data="employeeData"
            style="width: 100%"
            :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
          >
            <el-table-column
              prop="staffPhoto"
              label="头像"
              width="180"
            >
              <template #default="scope">
                <el-avatar v-if="scope.row.staffPhoto" :size="50" :src="scope.row.staffPhoto" />
                <span v-else style="display:block;width:40px;height:40px;background:#04c9be;color:white;border-radius:50%;line-height:40px;text-align:center">{{ scope.row.username.charAt(0) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="username"
              label="姓名"
              width="180"
            />
            <el-table-column
              prop="mobile"
              label="手机号"
              sortable
            />
            <el-table-column
              prop="workNumber"
              label="工号"
              sortable
            />
            <el-table-column
              prop="formOfEmployment"
              label="聘用形式"
            >
              <template #default="scope">
                {{ scope.row.formOfEmployment===1?'正式':'非正式' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="departmentName"
              label="部门"
            />
            <el-table-column
              prop="timeOfEntry"
              label="入职时间"
              sortable
            />
            <el-table-column

              label="操作"
              align="center"
            >
              <template #default="{row}">
                <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
                <el-button type="text" @click="showroleDialog(row.id)">角色</el-button>
                <el-button v-permission="'user_delete'" type="text" @click="del(row.id)">删除</el-button>
                <!-- 删除 -->
                <!-- &nbsp; -->
                <!-- <el-popconfirm
                  title="确定删除吗？"
                  @onConfirm="del(row.id)"
                >
                  <template #reference>
                    <el-button type="text">删除</el-button>
                  </template>
                </el-popconfirm> -->
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div style="text-align: right">
            <el-pagination
              layout="prev, pager, next,jumper,sizes"
              :total="total"
              :page-size="employeeParems.pagesize"
              :page-sizes="[10, 5, 20]"
              @current-change="changePage"
              @size-change="Sizechangge"
            />
          </div>
        </el-col>
      </el-row>
      <EmployeeImport :visible.sync="show" @getemployee="getemployee" />
      <!-- 添加角色框 -->
      <el-dialog title="分配角色" width="50%" :visible.sync="roleVisible">
        <el-form>
          <el-form-item>
            <el-checkbox-group v-model="selectRole">
              <el-checkbox v-for="item in roleRoes" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
              <!-- selectRole 数组中的数字对应的id会选中  ---label -->
            </el-checkbox-group>
          </el-form-item>
          <!--  -->
          <el-form-item>
            <el-button type="primary" @click="saveRole">确认</el-button>
            <el-button @click="roleVisible=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
// 按需引入debounce
import debounce from 'lodash/debounce'
import { getDepartments } from '@/api/department'
import { transListToTree } from '@/utils'
import { getemployee, exportExcel, delemployee, oneemployee, assignRole } from '@/api/employee'
import { saveAs } from 'file-saver'
import { getRoles } from '@/api/role'
import EmployeeImport from './component/EmployeeImport.vue'
// let timer = null
export default {
  name: 'Employee',
  components: {
    EmployeeImport
  },
  data() {
    return {
      id: null,
      roleRoes: [],
      selectRole: [],
      roleVisible: false,
      show: false,
      departmentList: [],
      employeeData: [],
      employeeParems: {
        page: 1,
        pagesize: 5
      },
      total: null,
      keyword: ''
    }
  },
  watch: {
    // keyword(newVal) {
    //   clearTimeout(timer)
    //   timer = setTimeout(() => {
    //     console.log(newVal)
    //   }, 500)
    // }
    keyword: debounce(function(newVal) {
      console.log(newVal)
      this.employeeParems.keyword = newVal
      this.getemployee()
    }, 500)
  },
  async created() {
    await this.getDepartments()
    this.$refs.tree.setCurrentKey(this.departmentList[0].id)
    await this.getemployee()
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      this.departmentList = transListToTree(res, 0)
      console.log(this.departmentList)
    },
    handleCurrentChange(data) {
      console.log(data)
      this.employeeParems.departmentId = data.id
      // this.$refs.tree.setCurrentKey(data.id)
      this.getemployee()
    },
    async getemployee() {
      const res = await getemployee(this.employeeParems)
      console.log(res)
      this.employeeData = res.rows
      this.total = res.total
    },
    changePage(page) {
      this.employeeParems.page = page
      this.getemployee()
    },
    Sizechangge(size) {
      this.employeeParems.pagesize = size
      this.getemployee()
    },
    async exportExcel() {
      const res = await exportExcel()
      console.log(res)
      saveAs(res, '员工信息表.xlsx')
    },
    async del(id) {
      await delemployee(id)
      this.$message.success('删除成功')
      this.getemployee()
    },
    // 增加角色
    async showroleDialog(id) {
      this.id = id
      const res = await getRoles({ page: 1, pagesize: 99999999999 })
      this.roleRoes = res.rows
      console.log(this.roleRoes)
      // 拿到员工的具体信息 信息中的roleIds表示的是员工权限
      const res1 = await oneemployee(id)
      this.selectRole = res1.roleIds
      this.roleVisible = true
      console.log(id)
    },
    // 添加权限
    async saveRole() {
      await assignRole({ id: this.id, roleIds: this.selectRole })
      this.$message.success('修改成功')
      this.roleVisible = false
    }
  }
}
</script>
